package com.eschool.beans.converter;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.ConverterException;

import com.eschool.dao.RoleDao;
import com.eschool.dao.UserDao;
import com.eschool.model.Role;
import com.eschool.model.User;
import com.eschool.util.ConstraintsUtil;
import com.eschool.util.UserUtil;

public class UserConverter implements Converter {

	public static List<User> users;

	public UserConverter(int id) {
		users = new ArrayList<User>();
		
		// -- If user's list is required by a Customer, adding the branch constraint
		if ( UserUtil.currentUser() != null )
			users = UserDao.getUsersUsingOr(getConstraintsMap());
		// -- else providing the complete list of users to the SaaS Admin
		else
			users = UserDao.getUsers(getConstraintsMap());
	}

	@Override
	public Object getAsObject(FacesContext facesContext, UIComponent component,
			String submittedValue) {
		// TODO Auto-generated method stub
		if (submittedValue.trim().equals("")) {
			return null;
		} else {
			try {
				for (User u : users) {
					if (u.getName().equalsIgnoreCase(submittedValue)) {
						return u;
					}
				}

			} catch (NumberFormatException exception) {
				throw new ConverterException(new FacesMessage(
						FacesMessage.SEVERITY_ERROR, "Conversion Error",
						"Not a valid User"));
			}
		}
		return null;
	}

	@Override
	public String getAsString(FacesContext facesContext, UIComponent component, Object value) {
		// TODO Auto-generated method stub
		if (value == null || value.equals("")) {
			return "";
		} else {
			return ((User) value).getName();
		}
	}
	
	private Map getConstraintsMap() {
		
		Map<String , Object> constraints = new HashMap<String, Object>();
		
		if ( UserUtil.currentUser() != null ) {
			constraints.put("role", RoleDao.getRoleByProperty("roleId", 4));
			constraints.put("role2", RoleDao.getRoleByProperty("roleId", 3));
			constraints.put("branch", UserUtil.currentUser().getBranch());
		}
		// This is for SaaS admin changing passwords of School Admins
		else {
			constraints.put("role", RoleDao.getRoleByProperty("roleId", 2));
		}
		
		return constraints;
	}

}
